package com.codefish.codefishseckill.utils;

import com.codefish.codefishseckill.entity.AuthUser;
import com.codefish.codefishseckill.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * jwt token工具类
 *
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/09/13 下午 04:35
 */
public class JwtUtils {
    private static final String SECRET_KEY = "daydayup";
    private static final String ISSUER = "codefish";

    private static final String IDENTIFICATION_KEY = "identification";

    /**
     * 2h有效时间
     */
    public static final long DEFAULT_EXPIRE_TIME = 2 * 60 * 60 * 1000;

    public static String issueJwtToken(AuthUser userInfo) {
        return Jwts.builder().signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .setSubject(userInfo.getUsername())
                .setIssuer(ISSUER)
                .claim(IDENTIFICATION_KEY, userInfo.getPermissions().get(0).getAuthority())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + DEFAULT_EXPIRE_TIME)).compact();
    }

    public static User parseJwtToken(String jwtToken) {
        Jws<Claims> jws = Jwts.parser().setSigningKey(SECRET_KEY)
                .parseClaimsJws(jwtToken);
        Claims claims = jws.getBody();
        User user = new User();
        user.setUsername(Long.parseLong(claims.getSubject()));
        user.setIdentification(claims.get(IDENTIFICATION_KEY, String.class));
        return user;
    }

}
